local function get_real_x(max_w,index,max,w,gap)
    local gap = gap or 50
    local x0 = (max_w - max*w - (max-1)*gap)/2
    return x0 + (index-1)*(w+gap)
end

--选择英雄
local ui = class.panel.create('',(1920 - 400)/2,200,500,250)
ui:hide()
ui:set_level(99)
ui:add_frame('tooltip_backdrop0')
ui:add_text('|cff00ff00选择奖励|r',0,10,nil,30,16,5)
ui:add_text('|cffdf9999从以下选择一个|r',0,50,nil,30,10,5)
ui.buttons = {}
for a=1,3 do
    local x = get_real_x(ui.w,a,3,80,70)
    local button = ui:add_button([[ReplaceableTextures\CommandButtons\BTNSpellBreakerMagicDefend.blp]],x,(ui.h-80)/2,80,80)
    button:set_highlight([[UI\Widgets\BattleNet\bnet-button01-highlight-mouse.blp]])
    button.title = button:add_text('装备名称',-35,button.h,button.w+70,30,12,5)
    button.index = a
    ui.buttons[a] = button
end

function ui:set_data(list)
    for a,button in ipairs(self.buttons) do
        local skill = list[a]
        button.skill = skill
        if skill then
            button:set_normal_image(skill.art)
            button.title:set_text(skill:get_title())
        else
            button:set_normal_image([[ReplaceableTextures\CommandButtons\BTNCancel.blp]])
            button.title:set_text('')
        end
        if button:has_mouse() then
            button:notify('on_button_mouse_enter')
        end
    end
    self:show()
end

function ui:on_button_clicked(button)
    local index = button.index
    if index and button.skill then
        ac.sync('同步-选择装备',index)
        self:hide()
    end
end

function ui:on_button_mouse_enter(button)
    if button and button.skill then
        local skill = button.skill
        local tip = skill:get_tip()
        self:tooltip(skill.title or skill.name,tip)
    end
end


ac.sync:event '同步-选择装备'(function(_,player,index)
    local list = player:get_data('选择装备列表')
    local temp = list and list[index]
    local unit = list and list._unit
    if temp then
        player:set_data('选择装备列表',nil)
        unit:add_item(temp.name)
    end
end)

ac.game:event '玩家-随机选择装备'(function(_,player,data)
    player:set_data('选择装备列表',data)
    if player:is_self() then
        ui:set_data(data)
    end
end)